import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';

import '../../common/index.dart';

class MyPage extends ConsumerStatefulWidget {
  const MyPage({super.key});

  @override
  ConsumerState<MyPage> createState() => _MyPageState();
}

class _MyPageState extends ConsumerState<MyPage> with WidgetsBindingObserver {
  List<ShareEntity> _likedShares = [];
  bool _isLoading = true;
  String? _lastLikeListHash; // 用于检测点赞列表变化

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadLikedShares();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台回到前台时刷新数据
    if (state == AppLifecycleState.resumed) {
      _loadLikedShares();
    }
  }

  Future<void> _loadLikedShares() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null && currentUser.like.isNotEmpty) {
      try {
        final shares = await ShareService.getSharesByIds(currentUser.like);
        // 按日期降序排序（最新的在前面）
        shares.sort(
          (a, b) => DateTime.parse(b.date).compareTo(DateTime.parse(a.date)),
        );

        if (mounted) {
          setState(() {
            _likedShares = shares;
            _isLoading = false;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _likedShares = [];
            _isLoading = false;
          });
        }
        debugPrint('加载喜欢的分享失败: $e');
      }
    } else {
      // 用户没有点赞的分享，清空列表
      if (mounted) {
        setState(() {
          _likedShares = [];
          _isLoading = false;
        });
      }
    }
  }

  /// 比较两个列表是否相等
  bool _listEquals<T>(List<T> list1, List<T> list2) {
    if (list1.length != list2.length) return false;
    for (int i = 0; i < list1.length; i++) {
      if (list1[i] != list2[i]) return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    // 检查用户点赞列表是否发生变化
    if (currentUser != null) {
      final currentHash = currentUser.like.join(',');
      if (_lastLikeListHash != currentHash) {
        _lastLikeListHash = currentHash;
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _loadLikedShares();
          }
        });
      }
    }

    // 监听用户变化，重新加载喜欢的分享
    ref.listen<UserEntity?>(currentUserProvider, (previous, next) {
      // 当用户的like列表发生变化时，重新加载数据
      if (previous != null &&
          next != null &&
          !_listEquals(previous.like, next.like)) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _loadLikedShares();
          }
        });
      }
    });

    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.myBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: currentUser == null
              ? _buildLoginPrompt()
              : _buildUserProfile(currentUser),
        ),
      ),
    );
  }

  /// 构建登录提示界面
  Widget _buildLoginPrompt() {
    return Stack(
      children: [
        // 登录提示内容
        Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 头像占位符
              Container(
                width: 120.w,
                height: 120.h,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white.withValues(alpha: 0.2),
                  border: Border.all(
                    color: Colors.white.withValues(alpha: 0.3),
                    width: 2.w,
                  ),
                ),
                child: Icon(
                  Icons.person_outline,
                  size: 60.w,
                  color: Colors.white.withValues(alpha: 0.7),
                ),
              ),

              SizedBox(height: 32.h),

              // 提示文字
              Text(
                'Welcome to IMMI',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 28.sp,
                  fontFamily: 'PoetsenOne',
                  fontWeight: FontWeight.w400,
                ),
              ),

              SizedBox(height: 12.h),

              Text(
                'Login to view your profile and\nmanage your favorite shares',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white.withValues(alpha: 0.8),
                  fontSize: 16.sp,
                  fontFamily: 'Manrope',
                  fontWeight: FontWeight.w400,
                  height: 1.5,
                ),
              ),

              SizedBox(height: 48.h),

              // 登录按钮
              InkWell(
                onTap: () {
                  AppRouterExtension(context).navigateTo(AppRoutes.login);
                },
                child: Container(
                  width: 280.w,
                  height: 48.h,
                  decoration: ShapeDecoration(
                    color: const Color(0xFFFF8C00),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24.r),
                    ),
                    shadows: [
                      BoxShadow(
                        color: const Color(0xFFFF8C00).withValues(alpha: 0.3),
                        blurRadius: 12.r,
                        offset: Offset(0, 4.h),
                      ),
                    ],
                  ),
                  child: Center(
                    child: Text(
                      'Login Now',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontFamily: 'Airbnb Cereal App',
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ),
              ),

              SizedBox(height: 16.h),

              // 注册提示
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Don\'t have an account? ',
                    style: TextStyle(
                      color: Colors.white.withValues(alpha: 0.7),
                      fontSize: 14.sp,
                      fontFamily: 'Manrope',
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      AppRouterExtension(
                        context,
                      ).navigateTo(AppRoutes.register);
                    },
                    child: Text(
                      'Sign up',
                      style: TextStyle(
                        color: const Color(0xFFFF8C00),
                        fontSize: 14.sp,
                        fontFamily: 'Manrope',
                        fontWeight: FontWeight.w600,
                        decoration: TextDecoration.underline,
                        decorationColor: const Color(0xFFFF8C00),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建用户资料界面
  Widget _buildUserProfile(UserEntity currentUser) {
    return Stack(
      children: [
        // 顶部设置按钮
        Positioned(
          top: 45.h,
          right: 10.w,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              InkWell(
                onTap: () {
                  AppRouterExtension(context).navigateTo(AppRoutes.subscribe);
                },
                child: Image.asset(
                  MyImages.vip,
                  width: 42.w,
                  height: 42.h,
                ),
              ),
              SizedBox(width: 18.w),
              InkWell(
                onTap: () {
                  AppRouterExtension(context).navigateTo(AppRoutes.setting);
                },
                child: SvgPicture.asset(
                  MyIcons.setting,
                  width: 24.w,
                  height: 24.h,
                ),
              ),
            ],
          ),
        ),

        // 用户信息
        Positioned(
          top: 78.h,
          left: -30.w,
          child: Container(
            width: 430.w,
            height: 352.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MyImages.userInfoBg),
                fit: BoxFit.contain,
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  width: 195.w,
                  height: 195.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(MyImages.avatarBg),
                      fit: BoxFit.contain,
                    ),
                  ),
                  child: Center(
                    child: UserAvatar(
                      radius: 32.r,
                      avatarPath: currentUser.avatar,
                    ),
                  ),
                ),
                SizedBox(
                  width: 107.w,
                  height: 40.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      currentUser.isVip == true
                          ? Image.asset(MyImages.vip, width: 32.w, height: 32.h)
                          : SizedBox(),
                      Text(
                        currentUser.username,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),

        // 用户的喜欢
        Positioned(
          top: 400.h,
          left: 0,
          right: 0,
          bottom: 0,
          child: Column(
            children: [
              Text(
                'My Likes',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: 'inter',
                  fontWeight: FontWeight.w600,
                  height: 1.05,
                  letterSpacing: 0.10,
                  decoration: TextDecoration.underline,
                  decorationColor: Color(0xFFFF8C00),
                  decorationThickness: 2.w,
                ),
              ),
              SizedBox(height: 16.h),

              // 用户喜欢的share
              Expanded(child: _buildLikedSharesList()),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建用户喜欢的分享列表
  Widget _buildLikedSharesList() {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator(color: Color(0xFFFF8C00)));
    }

    if (_likedShares.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.favorite_border,
              size: 48.w,
              color: Colors.white.withValues(alpha: 0.6),
            ),
            SizedBox(height: 16.h),
            Text(
              'No liked shares yet',
              style: TextStyle(
                color: Colors.white.withValues(alpha: 0.6),
                fontSize: 14.sp,
                fontFamily: 'inter',
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadLikedShares,
      child: ListView.builder(
        padding: EdgeInsets.only(
          left: 10.w,
          right: 10.w,
          top: 16.h,
          bottom: 65.h,
        ),
        itemCount: _likedShares.length,
        itemBuilder: (context, index) {
          final share = _likedShares[index];

          return GestureDetector(
            onTap: () async {
              // 增加浏览量
              await ref
                  .read(shareProvider.notifier)
                  .incrementViewCount(share.id);

              AppRouterExtension(context).navigateTo(
                AppRoutes.shareDetail,
                params: {'shareId': share.id},
              );
            },
            child: ShareItem(share: share, isSquare: false),
          );
        },
      ),
    );
  }
}
